/**************************************************************
  > File Name: recvcast.c
  > Author: LuoLiang
  > Mail: 1204553475@qq.com 
  > Created Time: 2022年03月09日 星期三 06时18分22秒
 **************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

#define BUFFSIZE 1024

int main(int argc, char **argv)
{
    if (argc < 3)
    {
        fprintf(stderr, "Usage:\n");
        exit(1);
    }
    
    int sockfd;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        perror("socket()");
        exit(1);
    }
    struct ip_mreq mreq;
    inet_pton(AF_INET, argv[1], &mreq.imr_multiaddr);
//    mreq.imr_interface.s_addr = htonl(INADDR_ANY);
    inet_pton(AF_INET, "192.168.31.208", &mreq.imr_interface);
    socklen_t len = sizeof(mreq);
    if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (void *)&mreq, len) < 0)
    {
        perror("setsockopt()");
        exit(1);
    }
    
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[2]));
    inet_pton(AF_INET, argv[1], &addr.sin_addr);
   
    socklen_t addrlen = sizeof(addr);
    if (bind(sockfd, (struct sockaddr *)&addr, addrlen) < 0)
    {
        perror("bind()");
        exit(1);
    }
       
    char recvbuff[BUFFSIZE] = {0};
    char *sendbuff = "recv over!";
    int ret;
    while (1)
    {
        ret = recvfrom(sockfd, recvbuff, BUFFSIZE, 0, (struct sockaddr *)&addr, &addrlen);
        if (ret > 0)
        {
            recvbuff[ret]  = '\0';
            puts(recvbuff);
        }
        sendto(sockfd, sendbuff, BUFFSIZE, 0, (struct sockaddr *)&addr, addrlen);
        memset(recvbuff, 0, BUFFSIZE);
    }
    close(sockfd);
    exit(0);
}
